<?php
/**
 * Created by PhpStorm.
 * User: anyuzhe
 * Date: 2017/4/1
 * Time: 10:04
 */

namespace App\ZL\Traites;


use App\Config;
use App\ZL\Library\Context;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

trait ControllerCRUDORG
{

    //----------------------------辅助方法-------------------------------

    //管道方法 进行模型处理过程
    protected function modelPipeline(array $pipes,$model=false)
    {
        $model = !$model?$this->getModel():$model;
        foreach ($pipes as $pipe) {
            if(method_exists($this, $pipe)){
                $model = $this->$pipe($model);
            }
        }
        return $model;
    }


    //判断和应用子类中的限制
    protected function modelGetAuthLimit(&$model)
    {
        if(method_exists($this,'authLimit')){
            $where = $this->authLimit($model);
            if($where){
                $model = $model->where($where);
            }
        }
        return $model;
    }

    //获取 并且 搜索
    protected function modelGetSearch(&$model)
    {
        $merges = [];
        if(isset($this->search_field_array) && !empty($this->search_field_array)){
            $this->search_field_array[] = 'id';
            foreach ($this->search_field_array as $item) {
                $this->getModelBySearchItem($model, $merges, $item);
            }
        }else{
            $_model = $this->getModel();
            if(isset($_model->fillable)){
                foreach ($_model->fillable as $item) {
                    $this->getModelBySearchItem($model, $merges, $item);
                }
                $this->getModelBySearchItem($model, $merges, 'id');
            }
        }
        if(count($merges)>0){
            $model = $model->where(function ($query)use($merges){
                $one = true;
                foreach ($merges as $item=>$_array) {
                    $p = is_array($_array[1])?$_array[1]:explode(',',$_array[1]);
                    if($one){
                        $one = false;
                        if(strtolower($_array[0])=='in'){
                            $query->whereIn($item, $p);
                        }elseif(strtolower($_array[0])=='exp'){
                            $query->whereRaw($this->mres($_array[1]));
                        }elseif(strtolower($_array[0])=='between'){
                            $query->whereBetween($item, $p);
                        }else{
                            $query->where($item,$_array[0],$_array[1]);
                        }
                    }else{
                        if(strtolower($_array[0])=='in'){
                            $query->orWhereIn($item, $p);
                        }elseif(strtolower($_array[0])=='between'){
                            $query->orWhereBetween($item, $p);
                        }else{
                            $query->orWhere($item,$_array[0],$_array[1]);
                        }
                    }
                }
            });
        }
        $start_date = request('start_date',null);
        $end_date = request('end_date',null);
        if($start_date && !$end_date){
            $model = $model->where('created_at','>',$start_date);
        }elseif (!$start_date && $end_date){
            $model = $model->where('created_at','<',$end_date);
        }elseif ($start_date && $end_date){
            $model = $model->where('created_at','>',$start_date);
            $model = $model->where('created_at','<',$end_date);
        }
        return $model;
    }


    public function getModelBySearchItem(&$model, &$merges, $item)
    {
        $_str = request($item,null);
        if($_str!==null){
            if(is_string($_str)){
                if(strstr($_str,'[')!==false || strstr($_str,'{')!==false){
                    $_array = json_decode($_str,true);
                }else{
                    $_array = explode(',',(string)$_str);
                }
            }else{
                $_array = $_str;
            }
            if(isset($_array[1])){
                $p = is_array($_array[1])?$_array[1]:explode(',',$_array[1]);
                if(isset($_array[2]) && $_array[2]){
                    $merges[$item] = $_array;
                }else{
                    if(strtolower($_array[0])=='in'){
                        $model = $model->whereIn($item, $p);
                    }elseif(strtolower($_array[0])=='exp'){
                        $model = $model->whereRaw($this->mres($_array[1]));
                    }elseif(strtolower($_array[0])=='between'){
                        $model = $model->whereBetween($item, $p);
                    }else{
                        $model = $model->where($item,$_array[0],$_array[1]);
                    }
                }
            }else{
                $model = $model->where($item,$_array[0]);
            }
        }
    }

    //排序
    protected function modelGetSort(&$model)
    {
        $sortBy = request('sortBy','id');
        $orderBy = request('orderBy','desc');
        $sortArr = explode(',',$sortBy);
        $orderArr = explode(',',$orderBy);
        foreach ($sortArr as $k=>$v) {
            $_orderBy = isset($orderArr[$k])?$orderArr[$k]:$orderBy;
            $sort_arr = explode('@',$v);
            if(isset($sort_arr[1])){
                $_sort = request($sort_arr[1],[]);
                if(is_array($_sort))
                    $_sort = implode(',', $_sort);
                $model = $model->orderByRaw($this->mres("FIELD($sort_arr[0], $_sort) $_orderBy"));
            }else{
                $model = $model->orderBy($v, $_orderBy);
            }
        }
//        $sort_model = clone $model;
//        $has_sort = $sort_model->first();
//        if($has_sort){
//            if(isset($has_sort->sort))
//                $model = $model->orderBy('sort','asc');
//        }
//        $model = $model->when($sortBy, function ($query) use ($sortBy,$orderBy){
//            return $query->orderBy($sortBy,$orderBy);
//        }, function ($query) use ($orderBy){
//            return $query->orderBy('id',$orderBy);
//        });
        return $model;
    }

    //根据分页 获取内容
    protected function modelGetPageData($model)
    {
        $pageSize = request('pageSize',20);
        $pagination = request('pagination',1);
        $pagination = $pagination>0?$pagination:1;
        //分页获取信息
        $list = $model->skip($pageSize*($pagination-1))->take($pageSize)->get();
        return $list;
    }

    //获取单个
    protected function modelFind($model)
    {
        return $model->first();
    }
    //获取单个根据id
    protected function modelFindById($model)
    {
        return $model->find(Context::get('id'));
    }

    //模型集合获取关联
    protected function collectionGetLoads(Collection &$list)
    {
        $req = request('loads','');
        $loads = $req?explode(',', $req):[];
        //加载关联
        if($list->count() && $loads && $this->model_load_array){
            foreach ($loads as $load) {
                if(in_array(lcfirst($load),$this->model_load_array)){
                    $list->load($load);
                }
            }
        }
        return $list;
    }

    //模型获取关联
    protected function modelFindLoads($data)
    {
        $req = request('loads','');
        $loads = $req?explode(',', $req):[];

        if($loads && $this->model_load_array && $data){
            //加载关联
            foreach ($loads as $load) {
                if (in_array(lcfirst($load), $this->model_load_array)) {
                    $data->$load;
                }
            }
        }
        return $data;
    }

    //模型集合后置转换
    protected function modelByAfterGet(Collection &$list)
    {
        //判断和应用子类中的字段转换
        if(method_exists($this,'_after_get') && $list->count()) {
            $list = $this->_after_get($list);
        }
        if($list instanceof Collection){
            return $list->toArray();
        }
        return $list;
    }
    //模型集合后置转换
    protected function modelByAfterFind($data)
    {
        //判断和应用子类中的字段转换
        if(method_exists($this,'_after_find') && $data) {
            $this->_after_find($data);
        }
        return $data;
    }

    public function getModelArray($table_name,$key,$value,$title,$where=[],callable $func=null)
    {
        $data = [];
        $data[] = $title;
        $models = DB::table($table_name)->where('is_delete',0)->where($where)->get();
        foreach ($models as $model) {
            if(is_array($value)){
                $__value = '';
                foreach ($value as $vv) {
                    $__value .= $model->{$vv};
                }
                $data[$model->{$key}] = $__value;
            }else{
                $data[$model->{$key}] = $model->{$value};
            }
            if($func!==null){
                $data[$model->{$key}] .= '-'.$func($model);
            }
        }
        return $data;
    }

    public function mres($var){

        if (get_magic_quotes_gpc()){
            $var = stripslashes(trim($var));
        }

        if(function_exists("mysql_real_escape_string")){
            $var = mysql_real_escape_string($var);
        }

        return trim($var);
    }
}